
<template>
  <div class="device-control">
    <h2>设备控制</h2>

    <!-- 新增设备按钮 -->
    <el-button type="primary" @click="openAddDialog">新增设备</el-button>

    <!-- 搜索框
    <el-input
      v-model="searchQuery"
      placeholder="搜索设备..."
      prefix-icon="el-icon-search"
      style="margin-bottom: 20px; margin-top: 20px;width: 300px;"
    ></el-input> -->

    <!-- 设备列表 -->
    <el-table :data="filteredDevices" style="width: 100%" class="table-container" empty-text="暂无数据">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="设备名称"></el-table-column>
      <el-table-column prop="sn" label="设备SN"></el-table-column>
      <el-table-column prop="address" label="设备地址"></el-table-column>
      <el-table-column prop="type" label="设备类型"></el-table-column>
      <el-table-column prop="system" label="所属系统"></el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-button
            size="small"
            :type="scope.row.status === 'ON' ? 'success' : 'plain'"
            @click="toggleDevice(scope.$index, scope.row, 'ON')"
          >
            开启
          </el-button>
          <el-button
            size="small"
            :type="scope.row.status === 'OFF' ? 'danger' : 'plain'"
            @click="toggleDevice(scope.$index, scope.row, 'OFF')"
          >
            关闭
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" @click="editDevice(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteDevice(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑设备模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="formDevice" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="formDevice.name"></el-input>
        </el-form-item>
        <el-form-item label="设备SN">
          <el-input v-model="formDevice.sn"></el-input>
        </el-form-item>
        <el-form-item label="设备地址">
          <el-input v-model="formDevice.address"></el-input>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-input v-model="formDevice.type"></el-input>
        </el-form-item>
        <el-form-item label="所属系统">
          <el-input v-model="formDevice.system"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { getDevices, sendCommand, addDevice as apiAddDevice, updateDevice, deleteDevice as apiDeleteDevice } from '@/api/alarmManage';

interface Device {
  id?: number;
  name: string;
  sn: string;
  address: string;
  type: string;
  system: string;
  status: string; // 修改为字符串类型 "ON" 或 "OFF"
}

@Component({
  name: 'device'
})
export default class DeviceControl extends Vue {
  private devices: Device[] = [];
  private formDevice: Device = {
    name: '',
    sn: '',
    address: '',
    type: '',
    system: '',
    status: 'OFF'
  };
  private dialogVisible = false;
  private isEditing = false;
  private searchQuery = '';

  async mounted() {
    await this.fetchDevices();
  }

  private async fetchDevices() {
    try {
      const response = await getDevices();
      console.log('API Response:', response); // 打印 API 响应
      if (Array.isArray(response)) {
        this.devices = response.map((device: any) => ({
          id: device.id,
          name: device.name,
          sn: device.sn,
          address: device.address,
          type: device.type,
          system: device.system,
          status: device.status // 直接赋值字符串 "ON" 或 "OFF"
        }));
        console.log('Parsed Devices:', this.devices); // 打印解析后的数据
      } else {
        console.error('Invalid data format:', response);
      }
    } catch (error) {
      console.error('Failed to fetch devices:', error);
    }
  }

  private async toggleDevice(index: number, device: Device, command: string) {
    try {
      console.log(`Sending Command: ${command} for SN: ${device.sn}`);
      await sendCommand({ sn: device.sn, command });
      console.log(`Command Sent Successfully`);
      // 如果命令成功，更新本地状态
      this.$set(this.devices[index], 'status', command); // 使用 Vue.set 更新状态
      console.log(`Updating Status: ${command} for SN: ${device.sn}`);
    } catch (error) {
      console.error('Failed to send command:', error);
      console.log(`Reverting Status: ${device.status} for SN: ${device.sn}`);
      // Revert the switch state if the command fails
      // No need to revert here as we are not changing the UI directly based on command failure
    }
  }

  private openAddDialog() {
    this.isEditing = false;
    this.formDevice = {
      name: '',
      sn: '',
      address: '',
      type: '',
      system: '',
      status: 'OFF'
    };
    this.dialogVisible = true;
  }

  private editDevice(index: number, device: Device) {
    this.isEditing = true;
    // 复制设备对象以避免直接修改原始数据
    this.formDevice = { ...device };
    this.dialogVisible = true;
  }

  private async submitForm() {
    try {
      if (this.isEditing) {
        console.log('Saving Edited Device:', this.formDevice);
        if (!this.formDevice.id) {
          throw new Error('Device ID is missing');
        }
        const response = await updateDevice(this.formDevice.id, this.formDevice);
        console.log('Device Updated Successfully:', response);
        // 如果更新成功，关闭模态框并重新获取设备列表
        this.dialogVisible = false;
        await this.fetchDevices();
      } else {
        console.log('Adding New Device:', this.formDevice);
        const response = await apiAddDevice(this.formDevice);
        console.log('New Device Added Successfully:', response);
        // 如果添加成功，清空表单并重新获取设备列表
        this.formDevice = {
          name: '',
          sn: '',
          address: '',
          type: '',
          system: '',
          status: 'OFF'
        };
        this.dialogVisible = false;
        await this.fetchDevices();
      }
    } catch (error) {
      console.error('Failed to perform operation:', error);
    }
  }

  private async deleteDevice(index: number, device: Device) {
    try {
      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log('Deleting Device:', device);
        if (!device.id) {
          throw new Error('Device ID is missing');
        }
        await apiDeleteDevice(device.id);
        console.log('Device Deleted Successfully');
        // 如果删除成功，移除设备并重新获取设备列表
        this.devices.splice(index, 1);
        await this.fetchDevices();
      }).catch(() => {
        console.log('Cancel Delete Operation');
      });
    } catch (error) {
      console.error('Failed to delete device:', error);
    }
  }

  get dialogTitle() {
    return this.isEditing ? '编辑设备' : '新增设备';
  }

  get filteredDevices() {
    return this.devices.filter(device =>
      device.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
      device.sn.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
      device.address.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
      device.type.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
      device.system.toLowerCase().includes(this.searchQuery.toLowerCase())
    );
  }
}
</script>

<style scoped>
.device-control {
  padding: 20px;
}
.table-container {
  justify-content: center;
  align-items: center;
}
.el-table {
  margin-top: 20px; /* 确保表格有适当的间距 */
}

.el-button-group {
  display: flex;
  gap: 5px;
}

.el-form {
  margin-bottom: 20px;
}
</style>